<template>
  <div class="conetr">
    <div class="center-board">
      <div class="center-title">
        <h3>施工关联</h3>
      </div>
      <div class="action-bar mb-[20px]">
        <el-button icon="Back" type="primary" plain text @click="backTo">返回</el-button>
        <el-button
          icon="Download"
          type="success"
          plain
          @click="handleSubmit"
          :disabled="!canEdit"
          :loading="loading"
        >
          保存
        </el-button>
      </div>
    </div>
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="150px"
      class="form mb-0"
      :disabled="!canEdit"
    >
      <el-form-item label="合同金额" prop="contractAmount">
        <el-input
          v-model.number="formData.contractAmount"
          type="number"
          placeholder="请输入合同金额"
        />
      </el-form-item>
      <el-form-item label="合同时间" prop="contractTime">
        <el-date-picker
          v-model="formData.contractTime"
          type="datetime"
          value-format="YYYY-MM-DD HH:mm:ss"
          placeholder="请选择合同时间"
        />
      </el-form-item>
      <el-form-item label="公司名称" prop="companyId">
        <!-- <el-input
          v-model.number="formData.companyId"
          type="number"
          placeholder="请输入选择公司"
        /> -->
        <el-select
          v-model="formData.companyId"
          filterable
          clearable
          style="width: 96%"
          placeholder="请选择装修公司"
          @change="handleChangeCompanyId"
        >
          <el-option
            v-for="item in decorationCompanyOptions"
            :key="item.id"
            :label="item.companyName"
            :value="item.id"
          />
        </el-select>
        <el-tooltip
          class="box-item"
          effect="dark"
          content="未找到您的公司可联系公司在团队管理中添加您的信息"
          placement="left"
        >
          <el-icon style="margin-left: 10px"><InfoFilled /></el-icon>
        </el-tooltip>
      </el-form-item>
      <el-form-item label="公司地址" prop="decorationAddress">
        <el-input v-model="formData.decorationAddress" placeholder="请输入地址" disabled />
      </el-form-item>
      <el-form-item label="施工合同" prop="contractFile">
        <FilesUpload
          v-model="formData.contractFile"
          :disabled="!canEdit"
          v-model:loading="contractFileLoading"
          :limit="20"
          @uploadSuccess="validateSingle('contractFile')"
          accept=".jpeg,.png,.jpg,.bmp,.pdf"
        ></FilesUpload>
        <!-- <MultiImageUpload
          v-model="formData.contractFile"
          :disabled="!canEdit"
          @uploadSuccess="validateSingle('contractFile')"
          v-model:loading="contractFileLoading"
          :limit="20"
        /> -->
      </el-form-item>
      <el-form-item label="收款凭证" prop="receiptFile">
        <MultiImageUpload
          v-model="formData.receiptFile"
          :disabled="!canEdit"
          @uploadSuccess="validateSingle('receiptFile')"
          v-model:loading="receiptFileLoading"
          :limit="2"
        />
      </el-form-item>
      <div v-if="formData.remark">
        <el-form-item label="驳回理由">
          {{ formData.remark }}
        </el-form-item>
      </div>
    </el-form>
  </div>
</template>
<script setup lang="ts">
import { ElMessage } from "element-plus";
import HouseAPI, { ConsumerHouseConstructionLinkForm } from "@/api/house";
import MultiImageUpload from "@/components/Upload/MultiImageUpload.vue";
import FilesUpload from "@/components/Upload/FilesUpload.vue";
import opportunityPaymentAPI from "@/api/opportunityPayment";

// 定义 emit，用于通知外部关闭事件
const emit = defineEmits(["update:modelValue", "loadData", "backTo"]);
const props = defineProps({
  // 1 是装修知识的type固定字段 2是装修案例
  merchantUserId: {
    type: Number,
    default: 1,
  },
});
const dialog = reactive({
  title: "",
  visible: false,
});
/*基础信息*/
const formRef = ref();
const currentRow = ref({});
const contractFileLoading = ref(false);
const paymentFileLoading = ref(false);
const receiptFileLoading = ref(false);
const defaultFormData: ConsumerHouseConstructionLinkForm = {
  companyId: undefined,
  contractAmount: undefined,
  contractTime: undefined,
  contractFile: [],
  createBy: undefined,
  createTime: "",
  decorationAddress: "",
  decorationCompanyName: "",
  designerName: "",
  designerPhone: "",
  houseId: undefined,
  id: "",
  merchantUserId: undefined,
  paymentFile: [],
  receiptFile: [],
  status: undefined,
  updateBy: 0,
  updateTime: "",
  remake: "",
};
const decorationCompanyOptions = ref([]);
const formData = ref({
  ...defaultFormData,
});
const formRules = reactive({
  contractAmount: [
    { type: "number", message: "合同金额必须为数字" },
    { type: "number", max: 999999999, message: "合同金额超出最大值" },
    { required: true, message: "请输入合同金额", trigger: "blur" },
  ],
  contractTime: [{ required: true, message: "请选择合同时间", trigger: "change" }],
  contractFile: [{ required: true, message: "请上传设计合同", trigger: "change" }],
  paymentFile: [{ required: true, message: "请上传付款凭证", trigger: "change" }],
  receiptFile: [{ required: true, message: "请上传收款凭证", trigger: "change" }],
});
const loading = computed(
  () => contractFileLoading.value || paymentFileLoading.value || receiptFileLoading.value
);
const validateSingle = (field: string) => {
  formRef.value.validateField(field);
};
function backTo() {
  emit("backTo");
}
async function handleSubmit() {
  const validate = await formRef.value.validate();
  if (!validate) return;
  try {
    await HouseAPI.houseConstructionLinkEdit({
      ...formData.value,
      contractFile: JSON.stringify(formData.value.contractFile),
      paymentFile: JSON.stringify(formData.value.paymentFile),
      receiptFile: JSON.stringify(formData.value.receiptFile),
    });
    ElMessage.success("成功");
    emit("loadData");
    emit("backTo");
    handleCloseDialog();
  } catch (error) {
    console.log("error", error);
  }
}

// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;
  Object.assign(formData.value, defaultFormData);
  emit("update:modelValue", false); // 关闭弹窗
}
const canEdit = ref(true);
function showModal(val, cannotEdit = false) {
  dialog.visible = true;
  currentRow.value = val;
  const { contractFile, paymentFile, receiptFile } = val.house.houseConstructionLinkVO || {};
  Object.assign(formData.value, defaultFormData, val.house.houseConstructionLinkVO, {
    houseId: val.houseId,
    contractFile: JSON.parse(contractFile || "[]"),
    paymentFile: JSON.parse(paymentFile || "[]"),
    receiptFile: JSON.parse(receiptFile || "[]"),
  });
  canEdit.value = !cannotEdit;
  getMerchant();
}

async function getMerchant() {
  try {
    const data = await opportunityPaymentAPI.getMerchantList({
      merchantUserId: props.merchantUserId,
    });
    decorationCompanyOptions.value = data;
  } catch (e) {
    console.log(e);
  }
}
function handleChangeCompanyId(val) {
  const { companyName, businessAddress } =
    decorationCompanyOptions.value.find((item) => item.id === val) || {};
  formData.value.decorationCompanyName = companyName;
  formData.value.decorationAddress = businessAddress;
}

defineExpose({
  showModal,
});
</script>
<style style="scss" scoped>
@import "@/views/house/style/conetr.scss";
.form-container {
  height: 600px;
  overflow: auto;
}
.form {
  ::v-deep(.el-form-item) {
    margin-bottom: 0;
  }
}
</style>
